#include "gameroom.h"
#include "gameselect.h"

#include<QPainter>
#include<QPixmap>
#include<QIcon>
#include<QTimer>
#include<QPushButton>
#include<QMessageBox>
#include<QFile>
#include<QTextStream>


GameRoom::GameRoom(QWidget *parent) : QWidget(parent)
{

    this->setFixedSize(1000,800);
    this->setWindowIcon(QIcon(":res/ico.png"));
    this->setWindowTitle("游戏房间");

    //初始化贪吃蛇
    snakeList.push_back(QRectF(this->width() / 2,this->height() / 2,ksnakeNodeWidth,ksnakeNodeHeight));

    moveUp();
    moveUp();

    //创建食物
    createNewFood();

    timer = new QTimer(this);

    connect(timer,&QTimer::timeout,[=](){
        int cnt = 1;

        if(snakeList.front().intersects(foodRect))
        {
            createNewFood();
            cnt++;
            QSound::play(":res/eatfood.wav");
        }
        while(cnt--)
        {
            switch(moveDirect)
            {
            case SnakeDirect::UP:
                moveUp();
                break;
            case SnakeDirect::DOWN:
                moveDown();
                break;
            case SnakeDirect::LEFT:
                moveLeft();
                break;
            case SnakeDirect::RIGHT:
                moveRight();
                break;
            }
        }

        snakeList.pop_back();
        update();
    });

    //开始暂停游戏
    QPushButton *strBtn = new QPushButton(this);
    QPushButton *stopBtn = new QPushButton(this);

    strBtn->move(825,150);
    stopBtn->move(825,200);

    strBtn->setText("开始游戏");
    stopBtn->setText("暂停游戏");

    QFont font("楷体",20);
    strBtn->setFont(font);
    stopBtn->setFont(font);

    connect(strBtn,&QPushButton::clicked,[=](){
       isGameStart = true;
       timer->start(moveTimeout);
       sound = new QSound(":res/Trepak.wav");
       sound->play();
       sound->setLoops(-1);
    });


    connect(stopBtn,&QPushButton::clicked,[=](){
        isGameStart = false;
        timer->stop();
        sound->stop();
    });

    //方向控制
    QPushButton *up = new QPushButton(this);
    QPushButton *down = new QPushButton(this);
    QPushButton *left = new QPushButton(this);
    QPushButton *right = new QPushButton(this);

    up->move(880,400);
    down->move(880,480);
    left->move(840,440);
    right->move(920,440);

    up->setText("↑");
    down->setText("↓");
    left->setText("←");
    right->setText("→");


    up->setStyleSheet("QPushButton{border:0px;}");
    down->setStyleSheet("QPushButton{border:0px;}");
    left->setStyleSheet("QPushButton{border:0px;}");
    right->setStyleSheet("QPushButton{border:0px;}");

    QFont ft("宋体",28);
    up->setFont(font);
    down->setFont(font);
    left->setFont(font);
    right->setFont(font);

    connect(up,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::DOWN)
        {
            moveDirect = SnakeDirect::UP;
        }
    });

    connect(down,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::UP)
        {
            moveDirect = SnakeDirect::DOWN;
        }
    });

    connect(left,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::RIGHT)
        {
            moveDirect = SnakeDirect::LEFT;
        }
    });

    connect(right,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::LEFT)
        {
            moveDirect = SnakeDirect::RIGHT;
        }
    });

    //退出游戏
    QPushButton *ExitBtn = new QPushButton(this);
    ExitBtn->move(860,750);
    ExitBtn->setText("退出");
    ExitBtn->setFont(font);


    QMessageBox *msg = new QMessageBox(this);
    QPushButton *ok = new QPushButton("ok");
    QPushButton *cancel = new QPushButton("cancel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);

    msg->setWindowTitle("退出游戏");
    msg->setText("确认退出游戏吗?");

    connect(ExitBtn,&QPushButton::clicked,[=](){
        msg->show();
        msg->exec();
        QSound::play(":res/clicked.wav");

        GameSelect *select = new GameSelect;

        if(msg->clickedButton() == ok)
        {
            this->close();
            select->show();
        }
        else
        {
            msg->close();
        }
    });

}


void GameRoom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pixmap;
    pixmap.load(":res/game_room.png");
    painter.drawPixmap(0,0,800,800,pixmap);
    pixmap.load(":res/bg1.png");
    painter.drawPixmap(800,0,200,900,pixmap);

    //绘制蛇
    //蛇头
    if(moveDirect == SnakeDirect::UP)
    {
        pixmap.load(":res/up.png");
    }
    else if(moveDirect == SnakeDirect::DOWN)
    {
        pixmap.load(":res/down.png");
    }
    else if(moveDirect == SnakeDirect::LEFT)
    {
        pixmap.load(":res/left.png");
    }
    else
    {
        pixmap.load(":res/right.png");
    }

    auto snakeHead = snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pixmap);

    //蛇身
    pixmap.load(":res/Bd.png");
    for (int i = 1; i < snakeList.size();i++)
    {
        auto node =snakeList.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pixmap);

    }

    //蛇尾
    auto snakeTail = snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pixmap);

    //绘制食物
    pixmap.load(":res/food.bmp");
    painter.drawPixmap(foodRect.x(),foodRect.y(),foodRect.width(),foodRect.height(),pixmap);

    //绘制分数
    pixmap.load(":res/sorce_bg.png");
    painter.drawPixmap(this->width()*0.85,this->height()*0.06,90,40,pixmap);

    QPen pen;
    pen.setColor(Qt::blue);
    painter.setPen(pen);
    QFont font("方正舒体",26);
    painter.setFont(font);
    painter.drawText(this->width()*0.9,this->height()*0.1,QString("%1").arg(snakeList.size()));


    //往文件中写入分数
    int c = snakeList.size();
    QFile file("C:\\Users\\86187\\Desktop\\Snake\\history\\score.txt");
    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream out(&file);
        int num = c;
        out<<num;
        file.close();
    }




    //绘制游戏失败
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setPen(pen);
        QFont font("方正舒体",50);
        painter.setFont(font);
        painter.drawText(this->width()*0.45,this->height()*0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":res/gameover.wav");

        sound->stop();
    }

}

void GameRoom::moveUp()
{
    QPointF leftTop;
    QPointF rightBottom;
    auto snakeNode = snakeList.front();

    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(heady < 0)
    {
        leftTop = QPointF(headx,this->height()-ksnakeNodeHeight);
    }
    else
    {
        leftTop = QPointF(headx,heady-ksnakeNodeHeight);
    }
    rightBottom =leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveDown()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();

    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(heady > this->height())
    {
        leftTop = QPointF(headx,0);
    }
    else
    {
        leftTop = snakeNode.bottomLeft();
    }

    rightBottom = leftTop +QPointF(ksnakeNodeWidth,ksnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveLeft()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();

    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(headx < 0)
    {
        leftTop = QPointF(800 - ksnakeNodeWidth,heady);
    }
    else
    {
        leftTop = QPointF(headx - ksnakeNodeWidth,heady);
    }

    rightBottom =  leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void GameRoom::moveRight()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeNode = snakeList.front();

    int headx = snakeNode.x();
    int heady = snakeNode.y();

    if(headx + ksnakeNodeWidth > 780)
    {
        leftTop =QPointF(0,heady);
    }
    else
    {
        leftTop = snakeNode.topRight();
    }

    rightBottom = leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

bool GameRoom::checkFail()
{
    for( int i = 0; i < snakeList.size();i++)
    {
        for(int j = i + 1; j< snakeList.size(); j++)
        {
            if(snakeList.at(i) == snakeList.at(j))
            {
                return true;
            }
        }
    }
    return false;
}

void GameRoom::createNewFood()
{
    foodRect = QRectF(qrand() % (800 / ksnakeNodeWidth) * ksnakeNodeWidth,
                      qrand() % (this->height() / ksnakeNodeHeight) * ksnakeNodeHeight,
                      ksnakeNodeWidth,ksnakeNodeHeight);

}









